package ru.minidoc.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import ru.minidoc.dao.DocumentDao;
import ru.minidoc.dao.DocumentHistoryDao;
import ru.minidoc.model.Document;
import ru.minidoc.model.json.DocumentList;

@Controller
public class DocumentHistoryController {
    @Autowired
    private DocumentDao documentDao;

    @Autowired
    private DocumentHistoryDao documentHistoryDao;

    @RequestMapping(value = "/document/history/read.action", method = RequestMethod.GET)
    public @ResponseBody
    DocumentList read(@RequestParam("id") Integer id, ModelMap model) {
        Document document = documentDao.load(new Document(id));
        List<Document> documentList = documentHistoryDao.getHistoryList(document);
        return new DocumentList(documentList.size(), documentList);
    }

    @RequestMapping(value = "/document/history/load.action", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, String> load(@RequestBody Map<String, Integer> json) {
        Map<String, String> result = new HashMap<String, String>();
        String text = documentHistoryDao.getText(new Document(json.get("id")), json.get("version") );
        result.put("id", json.get("id").toString());
        result.put("version", json.get("version").toString());
        result.put("text", text);
        return result;
    }
}
